<template>
  <div class="collecting-exercise-container">
    <h2 class="mb-4">
      收藏题目
    </h2>

    <!-- 题目类型筛选 -->
    <div class="filter-section mb-4">
      <label>筛选类型：</label>
      <select
        v-model="filterType"
        class="filter-dropdown"
      >
        <option value="">
          全部
        </option>
        <option value="0">
          选择题
        </option>
        <option value="1">
          简答题
        </option>
      </select>
    </div>

    <!-- 使用 QuestionCard 替代 ExerciseShow -->
    <QuestionCard 
      title="我的收藏题目" 
      :questions="filteredQuestions"
    >
      <!-- 插槽：取消收藏按钮 -->
      <template #action="{ question }">
        <button 
          class="cancel-btn" 
          @click="handleCancelCollect(question.id)"
        >
          取消收藏
        </button>
      </template>
    </QuestionCard>

    <!-- 加载状态和错误信息 -->
    <div
      v-if="loading"
      class="loading"
    >
      加载中...
    </div>
    <div
      v-if="error"
      class="error"
    >
      {{ error }}
    </div>
  </div>
</template>

<script>
import QuestionCard from './QuestionCard.vue';
import axios from 'axios';

export default {
  components: { QuestionCard },

  props: {
    // 👇 添加这两行
    userId: {
      type: String,
      required: true
    },
    courseId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      collectingQuestions: [], // 原始收藏题目列表
      filterType: '', // 筛选类型（0: 选择题，1: 简答题，空: 全部）
      loading: false,
      error: null
    };
  },
  computed: {
    // 计算属性：根据类型筛选题目
    filteredQuestions() {
      if (!this.filterType) return this.collectingQuestions;
      const selectedType = Number(this.filterType);
      return this.collectingQuestions.filter(q => q.type === selectedType);
    }
  },
  mounted() {
    this.fetchCollectingQuestions();
  },
  methods: {
    // 获取收藏题目
    async fetchCollectingQuestions() {
      this.loading = true;
      this.error = null;

      try {
        const userId = this.userId; // 实际应从登录状态获取
        const courseId = this.courseId; // 实际应从课程信息获取

         console.log('请求参数:', { userId, courseId }); // 👈 加这一行


        const response = await axios.get('/api/exercises/favorite', {
          params: { userId, courseId }
        });

        if (response.data && Array.isArray(response.data)) {
          this.collectingQuestions = response.data.map(question => {
            const { stem, options } = this.extractStemAndOptions(question.questionContent);

            return {
              id: question.questionId,
              type: question.type === false ? 0 : 1,
              score: question.questionScore,
              content: question.questionContent,
              answer: question.questionAnswer,
              stem,
              options
            };
          });
        } else {
          this.error = '收藏题目列表为空';
        }
      } catch (error) {
        this.error = '获取收藏题目失败，请重试';
        console.error(error);
      } finally {
        this.loading = false;
      }
    },

    // 提取选择题的题干和选项
    extractStemAndOptions(questionContent) {
      if (!questionContent || typeof questionContent !== 'string') {
        return {
          stem: '',
          options: []
        };
      }

      const lines = questionContent.split('\n').map(line => line.trim());
      let stem = '';
      const options = [];

      lines.forEach((line, index) => {
        if (index === 0 && !/^[A-D]\./i.test(line)) {
          stem = line; // 第一行作为题干
        } else if (/^[A-D]\./i.test(line)) {
          // 匹配 A. B. C. D.
          const option = line.replace(/^[A-D]\.\s*/i, '').trim();
          options.push(option);
        }
      });

      return {
        stem: stem || '这是一个选择题',
        options: options.length > 0 ? options : ['选项A', '选项B', '选项C', '选项D']
      };
    },

    // 取消收藏题目
    async handleCancelCollect(questionId) {
      if (!questionId) return;
      if (!window.confirm('是否移除收藏？')) return;

      try {
        await axios.post('/api/exercises/unfavorite', null,{
          params: {
            userId: this.userId,
            courseId: this.courseId,
            questionId: questionId
          }
        });

        this.collectingQuestions = this.collectingQuestions.filter(q => q.id !== questionId);
        console.log('取消收藏成功');
      } catch (error) {
        console.error('取消收藏失败:', error);
      }
    }
  }
};
</script>

<style scoped>
.collecting-exercise-container {
  padding: 2rem;
}

.filter-section {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.filter-dropdown {
  padding: 0.4rem 0.8rem;
  border: 1px solid #e4e7eb;
  border-radius: 4px;
  font-size: 0.9rem;
}

.cancel-btn {
  background-color: #ff4949;
  color: white;
  border: none;
  padding: 5px 10px;
  border-radius: 3px;
  cursor: pointer;
  font-size: 0.875rem;
  transition: opacity 0.2s;
}

.cancel-btn:hover {
  opacity: 0.8;
}

.loading {
  margin-top: 1rem;
  padding: 8px;
  color: #6c757d;
}

.error {
  margin-top: 1rem;
  color: #ff4d4f;
}
</style>
